<template>
    <div class="content">
        <div class="poster">
            <van-image
                :src="poster"
            />
        </div>

        <div class="link">
            <input type="text" placeholder="普通输入框" readonly id="url" :value="url" />   
            <button class="van-button van-button--primary van-button--small" type="button" @click="OnCopy">点击复制</button>
        </div>

        <div class="update">
            <van-button type="success" @click="OnUpdate">重新生成海报</van-button>
        </div>
    </div>
</template>

<script setup>
const { proxy } = getCurrentInstance();

// 获取用户数据
const business = proxy.$business;

// 推荐地址
const url = ref(proxy.$cookies.get('link') ? proxy.$cookies.get('link') : '');

// 获取用户海报
const poster = ref(business.value.poster ? business.value.poster_cdn : '');

// 挂载前
onBeforeMount(() => {
    if(!poster.value || !url.value)
    {
        GetPoster();
    }
})

// 请求海报
const GetPoster = async () =>
{
    // 获取当前域名
    let domain = location.origin ? location.origin : '';

    // 拼接推广地址
    domain = domain + '/business/login';

    // 组装参数
    let params = {
        busid:business.value.id,
        domain
    }

    let result = await proxy.$http.post({
        url:'/sale/poster',
        params
    })

    if(result.code === 1)
    {
        // 在海报地址加随机参数，防止重新生成不会更新图片
        poster.value = result.data.poster + '?random=' + Math.random();

        // 把推荐地址存储到cookie，方便每次进入页面获取地址
        proxy.$cookies.set('link',result.data.link);

        // 回显
        url.value = result.data.link;
    }else
    {
        proxy.$fail(result.msg);
    }
}

const OnCopy = () => 
{
    // 获取input
    let url = document.getElementById('url');

    // 选中地址
    url.select();
    
    // 让浏览器来执行copy命令
    document.execCommand('Copy') && proxy.$success('已复制到剪切板');
}

const OnUpdate = () =>
{
    proxy.$success({
        message:'更新海报成功',
        onClose:() =>
        {
            GetPoster();
        }
    });
}

</script>

<style scoped>
body{
    background-color: #eee;
}

.content{
    margin: 0 20px;
    padding: 20px 0;
}

.poster {
    width: 100%;
    margin-bottom: 20px;
}

.poster .van-image{
    width: 100%;
}

.link{
    width:90%;
    margin:0 auto;
    display: flex;
    justify-content: center;
    align-content: center;
    align-items: center;
    background:#fff;
    padding:10px;
}

.link button{
    display: inline-block;
    width:30%;
}

.link input{
    margin:0;
    margin-right:10px;
    border: none;
}

.update{
    text-align: center;
    margin: 20px auto 0;
}
</style>